package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.SecurityUserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.SecurityUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Service(interfaceClass = SecurityUserService.class)
@Transactional
public class SecurityUserServiceImpl implements SecurityUserService {

    @Autowired
    private SecurityUserDao securityUserDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    //用分部封装的方法查询用户相关信息（包括角色，权限）
    @Override
    public User findByUsername(String username) {
        //根据用户名查询用户
        User user = securityUserDao.findByUsername(username);
        if (user !=null) {
            Integer userId = user.getId();
            //根据用户id查询用户角色
            Set<Role> roles = roleDao.findByUserId(userId);
            //遍历角色id,根据角色查询用户权限
            for (Role role : roles) {
                Integer roleId = role.getId();
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                //将权限封装到角色
                role.setPermissions(permissions);
            }
            //将角色封装到用户
            user.setRoles(roles);
            return user;
        }else {
            return null;
        }
    }
}
